/**============================================================================
 Confidential Information - Limited distribution to authorized persons only.
 This software is protected as an unpublished work under the U.S. Copyright
 Act of 1976.

 Copyright (c) 2011, BluePhoenix Solutions, Inc. All rights reserved.
 ----------------------------------------------------------------------------
 file......: BaseTable.java
 Author....: Vyacheslav Kovalyov
 Created...: 27.10.11

 Description:

 ============================================================================*/
package ru.monyag.pred.swing.ui.table;

import ru.monyag.pred.swing.ui.ITable;
import ru.monyag.pred.swing.ui.ITableModel;

import javax.swing.*;
import javax.swing.table.TableColumn;
import java.util.ArrayList;
import java.util.List;

import static ru.monyag.pred.swing.util.PredSwingUtils.calculatePercentageSize;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
public class BaseTable<T> extends JTable implements ITable<T> {

    public BaseTable(BaseTableModel<T> model) {
        super(model);
        this.model = model;
    }

    @Override
    public void setData(List<T> data) {
        model.setData(data);
    }

    @Override
    public void updateRow(T object) {
        model.updateRow(object);
    }

    @Override
    public T getSelectedRowObject() {
        int selectedRow = getSelectedRow();
        if (selectedRow < 0) {
            return null;
        }
        return model.getRowObject(selectedRow);
    }

    @Override
    public void doLayout() {
        super.doLayout();
        setColumnWidths();
    }

    private void setColumnWidths() {

        List<TableColumn> autosizedColumns = new ArrayList<TableColumn>();
        int size = 0;

        for (int i = 0; i < getColumnCount(); i++) {
            Integer width = model.getModelInfo().getColumnWidth(i);

            if (width != null) {

                int calculatedWidth = calculatePercentageSize(getParent().getWidth(), width);
                getColumnModel().getColumn(i).setWidth(calculatedWidth);
                size += calculatedWidth;
            } else {
                autosizedColumns.add(getColumnModel().getColumn(i));
            }
        }

        int columnWidth = (getParent().getWidth() - size) / autosizedColumns.size();
        for (TableColumn col : autosizedColumns) {
            col.setWidth(columnWidth);
        }
    }

    private ITableModel<T> model;
}
